package com.muzi.weshop.view.fragment;

import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.muzi.weshop.R;
import com.muzi.weshop.common.LoginManager;
import com.muzi.weshop.common.base.BaseFragment;
import com.muzi.weshop.common.contants.BusConstants;
import com.muzi.weshop.common.contants.ExtraConstants;
import com.muzi.weshop.common.contants.RequestCodeContants;
import com.muzi.weshop.common.utils.DbUtils;
import com.muzi.weshop.model.BaseModel;
import com.muzi.weshop.model.GoodsModel;
import com.muzi.weshop.model.OrderRequestModel;
import com.muzi.weshop.view.activity.AddressActivity;
import com.muzi.weshop.view.activity.OrderListActivity;
import com.muzi.weshop.view.adapter.ShoppingCartAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.rubintry.speak.OkSpeaker;

/**
 * @author muzi
 * 购物车
 */
public class ShoppingCartFragment extends BaseFragment implements OnLoadMoreListener, CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "ShoppingCartFragment";
    private static final int REQUEST_CODE_SELECT_ADDRESS = 10001;
    private static final int RESULT_CODE_ADDRESS = 10002;
    @BindView(R.id.rvShoppingCart)
    RecyclerView rvShoppingCart;
    @BindView(R.id.ckSelectAll)
    CheckBox ckSelectAll;
    @BindView(R.id.tvTotalPrice)
    TextView tvTotalPrice;
    @BindView(R.id.tvEdit)
    TextView tvEdit;
    @BindView(R.id.tvDeleteGoods)
    TextView tvDeleteGoods;
    @BindView(R.id.tvCommitOrder)
    TextView tvCommitOrder;


    /**
     * 是否处于编辑状态
     */
    private boolean isEditing;
    private List<GoodsModel> orderList;
    /**
     * 需要结账的商品
     */
    private List<GoodsModel> needPayGoods;
    private ShoppingCartAdapter shoppingCartAdapter;
    /**
     * 总价格
     */
    private int totalPrice = 0;

    /**
     * 商品总数量
     */
    private int totalCount = 0;

    private boolean isComeFromGoodsDetail = false;


    private boolean isDeleting;


    @Override
    protected int attachedLayoutRes() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    protected void initData() {
        orderList = DbUtils.getInstance().queryAllGoods();
        needPayGoods = new ArrayList<>();
    }

    @Override
    protected void initViews() {
        BusUtils.register(this);
        isEditing = false;
        rvShoppingCart.setLayoutManager(new LinearLayoutManager(getContext()));
        rvShoppingCart.setNestedScrollingEnabled(false);
        orderList = new ArrayList<>();
        shoppingCartAdapter = new ShoppingCartAdapter(R.layout.item_shopping_cart, orderList);
        rvShoppingCart.setAdapter(shoppingCartAdapter);
        shoppingCartAdapter.setOnItemClickListener(new ShoppingCartAdapter.OnItemClickListener() {
            @Override
            public void onAddClick(int count, GoodsModel goodsModel, TextView tvGoodsCount) {

                count++;
                tvGoodsCount.setText(count + "");
                //android本地的数据库缓存（Greendao）
                goodsModel.setCount(count);


                if (DbUtils.getInstance().queryGoodsById(goodsModel.getId()).size() > 0) {
                    DbUtils.getInstance().updateGoods(goodsModel);
                } else {
                    DbUtils.getInstance().insertGoods(goodsModel);
                }


                if (goodsModel.getSelected()) {
                    totalCount++;
                    totalPrice += goodsModel.getPrice();
                }


                tvTotalPrice.setText("合计：￥" + totalPrice + ".00");
                tvCommitOrder.setText("提交订单(" + totalCount + ")");
            }

            @Override
            public void onReduceClick(int count, GoodsModel goodsModel, TextView tvGoodsCount) {


                //点击减号的时候
                if (count > 1) {
                    count--;
                    goodsModel.setCount(count);
                    tvGoodsCount.setText(count + "");
                    if (DbUtils.getInstance().queryGoodsById(goodsModel.getId()).size() > 0) {
                        DbUtils.getInstance().updateGoods(goodsModel);
                    } else {
                        DbUtils.getInstance().insertGoods(goodsModel);
                    }


                    if (goodsModel.getSelected()) {
                        totalCount--;
                        if (totalPrice >= goodsModel.getPrice()) {
                            totalPrice -= goodsModel.getPrice();
                        }
                    }


                    tvTotalPrice.setText("合计：￥" + totalPrice + ".00");
                    tvCommitOrder.setText("提交订单(" + totalCount + ")");

                } else {
                    ToastUtils.showShort("最少买一件哦");
                }
            }

            @Override
            public void onChecked(boolean isChecked, GoodsModel goodsModel) {

                goodsModel.setSelected(isChecked);

                DbUtils.getInstance().updateGoods(goodsModel);
                //打完√之后的
                if (isChecked) {
                    totalCount += goodsModel.getCount();

                    //统计总价
                    totalPrice += goodsModel.getPrice() * goodsModel.getCount();
                } else {

                    if (!isDeleting) {

                        totalCount -= goodsModel.getCount();
                        //统计总价
                        totalPrice -= goodsModel.getPrice() * goodsModel.getCount();

                    } else {
                        isDeleting = false;
                        goodsModel.setIsFromGoodsDetail(false);
                        DbUtils.getInstance().updateGoods(goodsModel);
                    }
                }
                tvCommitOrder.setText("提交订单(" + totalCount + ")");
                tvTotalPrice.setText("合计：￥" + totalPrice + ".00");


            }

        });

        ckSelectAll.setOnCheckedChangeListener(this);

    }

    @Override
    protected void requestData() {
    }


    /**
     * 当这个fragment显示在用户面前时，调用这个生命周期方法
     */
    @Override
    public void onResume() {

        isDeleting = false;
        if (!isComeFromGoodsDetail) {
            totalPrice = 0;
            totalCount = 0;
            tvCommitOrder.setText("提交订单(" + totalCount + ")");
            tvTotalPrice.setText("合计：￥" + totalPrice + ".00");
        }
        totalCount = 0;
        loadCacheData();
        super.onResume();
    }


    /**
     * 加载缓存数据
     */
    private void loadCacheData() {
        orderList.clear();
        List<GoodsModel> cachesGoodsList = DbUtils.getInstance().queryAllGoods();
        if (cachesGoodsList != null) {
            orderList.addAll(cachesGoodsList);
        }

            totalPrice = 0;
            totalCount = 0;

            for (GoodsModel goodsModel : orderList) {
                if (goodsModel.getSelected()) {
                    totalPrice += (goodsModel.getPrice() * goodsModel.getCount());
                    totalCount += goodsModel.getCount();
                }
            }

            tvTotalPrice.setText("合计：￥" + totalPrice + ".00");
            tvCommitOrder.setText("提交订单(" + totalCount + ")");
        shoppingCartAdapter.setNewData(orderList);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.ckSelectAll:
                if (isChecked) {
                    //选中全部
                    for (GoodsModel goodsModel : orderList) {
                        goodsModel.setSelected(true);
                    }
                    shoppingCartAdapter.setNewData(orderList);

                } else {
                    //取消全选
                    for (GoodsModel goodsModel : orderList) {
                        goodsModel.setSelected(false);
                    }
                    shoppingCartAdapter.setNewData(orderList);
                }
                totalPrice = 0;
                totalCount = 0;
                updateBottomData();
                break;
            default:
                break;
        }
    }


    @OnClick({R.id.tvCommitOrder, R.id.tvDeleteGoods, R.id.tvEdit})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvEdit:
                if (!isEditing) {
                    //进入编辑状态
                    isEditing = true;
                    tvEdit.setText("完成");
                    tvDeleteGoods.setVisibility(View.VISIBLE);
                } else {
                    isEditing = false;
                    tvEdit.setText("编辑");
                    tvDeleteGoods.setVisibility(View.GONE);

                }


                break;
            case R.id.tvDeleteGoods:

                //删除
                int orderCount = 0;
                isDeleting = true;
                for (int i = 0; i < orderList.size(); i++) {
                    if (orderList.get(i).getSelected()) {
                        DbUtils.getInstance().deleteGoods(orderList.get(i));
                        orderCount++;
                    }
                }

                //如果没有要删除的数据
                if (orderCount == 0) {
                    ckSelectAll.setChecked(false);
                }
                loadCacheData();
                updateBottomData();

                break;
            case R.id.tvCommitOrder:
                int selectedCount = 0;
                for (GoodsModel goodsModel : orderList) {
                    //如果这个商品数量大于0而且被选中了，说明要买
                    if (goodsModel.getCount() != 0 && goodsModel.getSelected()) {
                        selectedCount++;
                    }
                }
                if (selectedCount == 0) {
                    ToastUtils.showShort("最少勾选一件商品哦");
                    return;
                }
                startActivityForResult(new Intent(getContext(), AddressActivity.class), REQUEST_CODE_SELECT_ADDRESS);

                break;
            default:
                break;
        }
    }

    /**
     * 计算底部的合计 和  商品总数量
     */
    private void updateBottomData() {
//        if(!isEditing){
//            totalPrice = 0;
//            totalCount = 0;
//        }
        for (GoodsModel goodsModel : orderList) {
            if (goodsModel.getSelected()) {
                totalPrice += (goodsModel.getPrice() * goodsModel.getCount());
                totalCount += goodsModel.getCount();
            }
        }

        tvTotalPrice.setText("合计：￥" + totalPrice + ".00");
        tvCommitOrder.setText("提交订单(" + totalCount + ")");
    }

    private void goToPay(int id) {

        List<OrderRequestModel> orderRequestList = new ArrayList<>();
        //选中的条数
        int selectedCount = 0;
        needPayGoods.clear();
        for (GoodsModel goodsModel : orderList) {
            //如果这个商品数量大于0而且被选中了，说明要买
            if (goodsModel.getCount() != 0 && goodsModel.getSelected()) {
                //把结算掉的商品加到needPayGoods里，结算成功之后清除缓存
                needPayGoods.add(goodsModel);
                orderRequestList.add(new OrderRequestModel(id, goodsModel.getId(), goodsModel.getCount(), goodsModel.getPrice(), LoginManager.getInstance().getPersonalId()));
                selectedCount++;
            }
        }
        if (selectedCount == 0) {
            ToastUtils.showShort("最少勾选一件商品哦");
            return;
        }

        //下单接口
        apiPresenter.addOrder(orderRequestList, RequestCodeContants.ADD_ORDER);

    }


    @Override
    public void onNext(Object o, int requestCode) {
        super.onNext(o, requestCode);
        switch (requestCode) {
            case RequestCodeContants.ADD_ORDER:
                //结算
                BaseModel baseModel = (BaseModel) o;
                for (GoodsModel needPayGood : needPayGoods) {
                    DbUtils.getInstance().deleteGoods(needPayGood);
                }
                loadCacheData();
                if (baseModel.getCode() == 0) {
                    ToastUtils.showShort("结算成功");
                    OkSpeaker.get().speak("您的订单已结算成功，请耐心等待商家发货，感谢您的支持");
                    startActivity(new Intent(getContext(), OrderListActivity.class));
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SELECT_ADDRESS && resultCode == RESULT_CODE_ADDRESS) {
            int id = data.getIntExtra(ExtraConstants.SELECTED_ADDRESS_ID, 0);
            goToPay(id);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusUtils.unregister(this);
    }

    @BusUtils.Bus(tag = BusConstants.JUMP_TO_SHOPPING_CART, threadMode = BusUtils.ThreadMode.MAIN)
    public void comeFromGoodsDetail() {
        isComeFromGoodsDetail = true;
    }
}
